package app.biz.service.impl;

import app.biz.config.MongoDataSourceConfig;
import app.biz.model.ClientInfo;
import app.biz.model.EcgRequest;
import app.biz.service.atom.LogService;
import app.framework.util.ConcurrentUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.jfinal.kit.JsonKit;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/** Created by gulx@neusoft.com on 2018/12/5. */
@Service
public class LogServiceImpl implements LogService {

  private static final Logger logger = LoggerFactory.getLogger(LogServiceImpl.class);

  @Autowired
  MongoDataSourceConfig mongo;

  /** 默认线程池 */
  static ListeningExecutorService logPool = ConcurrentUtil.instance.getService();

  @Override
  public void bizlogAsync(EcgRequest ecgRequest, ClientInfo clientInfo) {
    try {
      logPool.submit(() -> getCollection().insertOne(
          new Document()
                  .append("sid", ecgRequest.getSid())
                  .append("content", JSONObject.toJSON(ecgRequest))
                  .append("ip", clientInfo.getRealIP())
                  .append("clientInfo", Document.parse(clientInfo.toString()))
                  .append("created", new Date())
                  .append("createdTime", System.currentTimeMillis())));
    } catch (Exception e) {
      logger.error("日志写入失败！！日志对象:\n{}", e, JsonKit.toJson(ecgRequest));
    }
  }

  @Override
  public Document queryBizlogBySID(long sid) {
    return getCollection().find(new Document("sid", sid)).first();
  }

  private MongoCollection<Document> getCollection() {
    return mongo.getCollecton("bizlog");
  }
}
